﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace Bootloader.AppSettings
{
    /// <summary>
    /// 应用配置类，支持数据绑定和 JSON 序列化
    /// </summary>
    public class AppConfig : INotifyPropertyChanged
    {
        // ========== 用户设置属性 ==========
        private int _channelSelIndex = 0;
        public int ChannelSelIndex
        {
            get => _channelSelIndex;
            set { _channelSelIndex = value; OnPropertyChanged(); }
        }

        private int _baudRateSelIndex = 0;
        public int BaudRateSelIndex
        {
            get => _baudRateSelIndex;
            set { _baudRateSelIndex = value; OnPropertyChanged(); }
        }

        private int _checksumMethodSelIndex = 0;
        public int ChecksumMethodSelIndex
        {
            get => _checksumMethodSelIndex;
            set { _checksumMethodSelIndex = value; OnPropertyChanged(); }
        }

        private int _udsAgreementSelIndex = 0;
        public int UDSAgreementSelIndex
        {
            get => _udsAgreementSelIndex;
            set { _udsAgreementSelIndex = value; OnPropertyChanged(); }
        }

        private string _phyAddrText = "745";
        public string PHYAddrText
        {
            get => _phyAddrText;
            set { _phyAddrText = value; OnPropertyChanged(); }
        }

        private string _funAddrText = "7DF";
        public string FUNAddrText
        {
            get => _funAddrText;
            set { _funAddrText = value; OnPropertyChanged(); }
        }

        private string _repAddrText = "74D";
        public string REPAddrText
        {
            get => _repAddrText;
            set { _repAddrText = value; OnPropertyChanged(); }
        }

        private string _appFilePath = "";
        public string AppFilePath
        {
            get => _appFilePath;
            set { _appFilePath = value; OnPropertyChanged(); }
        }

        private string _flashdriverFilePath = "";
        public string FlashdriverFilePath
        {
            get => _flashdriverFilePath;
            set { _flashdriverFilePath = value; OnPropertyChanged(); }
        }

        private string _sigFilePath = "";
        public string SigFilePath
        {
            get => _sigFilePath;
            set { _sigFilePath = value; OnPropertyChanged(); }
        }

        private string _dllFilePath = ".//Security.dll";
        public string DllFilePath
        {
            get => _dllFilePath;
            set { _dllFilePath = value; OnPropertyChanged(); }
        }

        // ========== 文件路径 ==========
        private static string ConfigFilePath
        {
            get
            {
                // 保存在 exe 同目录
                string exeDir = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
                return Path.Combine(exeDir, "settings.json");
            }
        }

        // ========== INotifyPropertyChanged ==========
        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged([System.Runtime.CompilerServices.CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        // ========== 批量加载（用于反序列化后赋值）==========
        public void LoadFrom(AppConfig source)
        {
            if (source == null) return;

            var props = typeof(AppConfig).GetProperties(BindingFlags.Public | BindingFlags.Instance)
                .Where(p => p.CanRead && p.CanWrite);

            foreach (var prop in props)
            {
                try
                {
                    var value = prop.GetValue(source);
                    if (!Equals(prop.GetValue(this), value))
                    {
                        prop.SetValue(this, value);
                    }
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine($"LoadFrom failed on '{prop.Name}': {ex.Message}");
                }
            }
        }

        // ========== 整体保存到文件 ==========
        // Save 方法
        public bool Save()
        {
            try
            {
                string json = JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented);
                File.WriteAllText(ConfigFilePath, json);
                return true;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"Save failed: {ex.Message}");
                return false;
            }
        }
        public bool Save(string configFilePath)
        {
            try
            {
                // 确保目录存在（关键！）
                string dir = Path.GetDirectoryName(configFilePath);
                if (!string.IsNullOrEmpty(dir))
                    Directory.CreateDirectory(dir); // 自动创建多级目录

                // 直接写入：文件不存在 → 创建；存在 → 覆盖
                string json = JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented);
                File.WriteAllText(configFilePath, json);
                return true;
            }
            catch
            {
                return false;
            }
        }

        // Load 方法
        public bool Load()
        {
            if (!File.Exists(ConfigFilePath)) return false;

            try
            {
                string json = File.ReadAllText(ConfigFilePath);
                var loaded = JsonConvert.DeserializeObject<AppConfig>(json);
                if (loaded != null)
                {
                    this.LoadFrom(loaded);
                    return true;
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"Load failed: {ex.Message}");
            }
            return false;
        }

        public bool Load(string ConfigFilePath)
        {
            if (!File.Exists(ConfigFilePath)) return false;

            try
            {
                string json = File.ReadAllText(ConfigFilePath);
                var loaded = JsonConvert.DeserializeObject<AppConfig>(json);
                if (loaded != null)
                {
                    this.LoadFrom(loaded);
                    return true;
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"Load failed: {ex.Message}");
            }
            return false;
        }
    }
}